"""
需求：使用cookie实现跳过登录
1). 手动登录淘宝，获取cookie
2). 使用获取到的cookie，达到登录目的，然后就可以执行登录之后的操作
"""
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 打开浏览器:谷歌
# service = Service(r"D://Python314//chromedriver.exe")
# chrome_options = Options()
# chrome_options.add_experimental_option("detach", True)
# driver = webdriver.Chrome(service=service, options=chrome_options)   # 创建浏览器对象
# 微软浏览器
driver = webdriver.Edge()

# 1. 访问淘宝域名（必须先打开目标网站，否则无法添加Cookie）
driver.get("https://www.taobao.com")
time.sleep(5)  # 等待页面加载
driver.maximize_window()  # 浏览器页面放大
time.sleep(5)

# 2. 完整Cookie字符串（1.先登录淘宝账号;2.在浏览器使用F12调出控制台;3.在控制台下输入document.cookie获取cookie内容，即cookie_str的值）
cookie_str="cna=peuMIfvZ9EcBASQOBHzsr4es;" \
           " mtop_partitioned_detect=1;" \
           " _m_h5_tk=a1fa4a3e7777d91b478bc28cb4abebbb_1762008213862; " \
           "_m_h5_tk_enc=bd455c4275f62b6db0f9b290b1d59e83; " \
           "sca=23107870; _m_h5_tk=54099f92a46d1eee28b8eac724c407a1_1762010014157;" \
           " _m_h5_tk_enc=c19c8cfe92a394169458dc60b82a3eee; arms_uid=55997247-7cf7-408a-9be1-83230818e45f; t=90fd3ae69f5f6da43407a8b17c871b38; _tb_token_=537e8147e58de; thw=xx; xlly_s=1; 3PcFlag=1762000315242; uc1=pas=0&cookie15=V32FPkk%2Fw0dUvg%3D%3D&cookie14=UoYY4dkb1SNZ6A%3D%3D&cookie16=W5iHLLyFPlMGbLDwA%2BdvAGZqLg%3D%3D&cookie21=VT5L2FSpczFp&existShop=false; sn=; csg=edc8929a; lgc=%5Cu6700%5Cu6700%5Cu6700%5Cu7231%5Cu767D%5Cu656C%5Cu4EAD; cancelledSubSites=empty; dnk=%5Cu6700%5Cu6700%5Cu6700%5Cu7231%5Cu767D%5Cu656C%5Cu4EAD; existShop=MTc2MjAwMDM1Ng%3D%3D; tracknick=%5Cu6700%5Cu6700%5Cu6700%5Cu7231%5Cu767D%5Cu656C%5Cu4EAD; _cc_=UtASsssmfA%3D%3D; _l_g_=Ug%3D%3D; sg=%E4%BA%AD2c; _nk_=%5Cu6700%5Cu6700%5Cu6700%5Cu7231%5Cu767D%5Cu656C%5Cu4EAD; aui=2200570955382; isg=BMvLHwz2JpRBNHpD0EuUI6XmWm-1YN_iogr4Bj3I_4phXOq-xDFHMnruMFyy_Dfa; tfstk=gqMtmET73eYMi2_NXqAHi2OVASt3MBmadVo5nr4GG23KV07gGrAZkS3m8SMgIc0dl2iz5i2_oSIxR2hg5-Yalt338hymsc2xHq2_gf40Srex04KHrLvobcy4CUYkEl0OLAw4lK2XtJwOC2IerLvobCZanDTos3jZmurlh-N_GwaQ8oE_logbdyZ8ROZfCo_BvozQhOZf1ysQ2lZ1hSgjAHE4RrwbhqwBvozQl-wjCISToGaAHfoDWaeMGtBAHvET6zB0JtBvmlFTPcapPUMpu5USfyBXWA6WcrUEFeAKY4csSkuveeeSa2HYN-pOzlhI2JagFdIaPAqxqjnJyZqE1VHQMvx2_DHYW7M_9GKsX-ZjlSheyTqTIXF-Bf-VRcguWbwZmgLiv7hLakNCD1wiZ0D4NA9OzyVzD2Fo6UBtPgznEYQ6ma48m1tpvs541kWo1amlFqAMJkUkx6fVgWqUvzxpvs541krLrHvhgsP3Y"

# 3. 关键：拆分Cookie为单个键值对，逐个添加（解决核心错误）
for cookie_item in cookie_str.split('; '):   # 按 "; " 分割Cookie字符串，得到每个独立的 "key=value"
    if '=' in cookie_item:  # 判断这个小片段里有没有
        key, value = cookie_item.split('=', 1)   # 按第一个 “=” 拆分，分成 “名字” 和 “值”（防止值里面有 “=” 导致拆错）
        # 构造单个Cookie字典
        single_cookie = {
            'name': key,   # Cookie 的名字
            'value': value,   # Cookie 对应的值
            'domain': '.taobao.com',  # 淘宝的通用域名，必须带前面的点
            'path': '/',  # Cookie 的生效范围
            'httpOnly': False,  # 适配大部分淘宝Cookie
            'secure': False     # 非HTTPS环境也能生效
        }
        try:  # 把Cookie加到浏览器里
            driver.add_cookie(single_cookie)
            print(f"成功添加Cookie: {key}")
        except Exception as e:
            # 忽略个别无效Cookie（如临时Cookie），不影响整体登录
            print(f"跳过Cookie {key}: {str(e)[:50]}")  # 只显示前50字符，避免输出过长

# 4. 刷新页面使Cookie生效
time.sleep(20)
driver.refresh()
time.sleep(20)

# 5. 退出浏览器
driver.quit()